package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    //根据用户名查询用户所有信息（包括角色和权限）
    /*
    方式一：之前有做过的多表关联查询
    方式二：挨个表查询然后自己封装，下面采用方式二
     */
    @Override
    public User fingByUsername(String username) {

        User user = userDao.fingByUsername(username);
        if(user == null){
            return null;
        }

        Integer userId = user.getId();

        Set<Role> roles = roleDao.findByUserId(userId);

        if(roles != null && roles.size()>0){
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if(permissions != null && permissions.size()>0){
                    //将权限装入角色中
                    role.setPermissions(permissions);
                }
            }

            //将角色装入用户中
            user.setRoles(roles);
        }

        return user;
    }
}
